package com.study.java._02anno_reflec.type.gsontest;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * <pre>
 *     author : slx
 *     time   : 2020/11/28
 *     desc   :
 * </pre>
 */
public class Deserialize {

    static class Response<T> {
        T data;
        int code;
        String msg;

        public Response(T data, int code, String msg) {
            this.data = data;
            this.code = code;
            this.msg = msg;
        }

        @Override
        public String toString() {
            return "Response{" +
                    "data=" + data +
                    ", code=" + code +
                    ", msg='" + msg + '\'' +
                    '}';
        }
    }

    static class Data {
        String data;

        public Data(String data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "Date{" +
                    "date='" + data + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws Exception {
        Response<Data> response = new Response<>(new Data("hello"), 1, "success");

        String json = new Gson().toJson(response);
        System.out.println(json);

        // 反序列化 可以官方TypeToken
        Response<Data> response1 = new Gson().fromJson(json, new TypeToken<Response<Data>>() {
        }.getType());

        // 自定义TypeToken
       /* Response<Data> response1 = new Gson().fromJson(json, new TypeRefrence<Response<Data>>() {
        }.getType());*/

        System.out.println(response1);
    }
}